package com.reflection.basic;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class Test {
	public static void getClassTest() throws ClassNotFoundException {
		Class<?> clazz = Example.class;
		System.out.println(clazz);
		
		Example example = new Example("name");
		clazz = example.getClass();
		System.out.println(clazz);
		
		clazz = Class.forName("com.reflection.basic.Example");
		System.out.println(clazz);
		
		clazz = Test.class.getClassLoader().loadClass("com.reflection.basic.Example");
		System.out.println(clazz);
	}
	
	@SuppressWarnings("unchecked")
	public static void newInstance() throws Exception {
		//获取类模板
		Class<?> clazz = Class.forName("com.reflection.basic.Example");
		//根据构造器的参数类型获取类的相应的构造器
		Constructor<Example> constructor = (Constructor<Example>)clazz.getConstructor(String.class);
		//通过构造方法获取对应的实例
		Example example = constructor.newInstance("your name");
		//通过类模板获取类方法
		Method getName = clazz.getDeclaredMethod("getName");
		//通过反射方式调用类的方法，第一个参数为类的实例
		Object name = getName.invoke(example);
		System.out.println(name);
	}
	
	public static void main(String[] args) throws Exception {
		newInstance();
	}
}
